package wan.com.templateproject.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author wan
 * @version 1.0.0
 * @Description 线程池配置
 * @createTime 2021年10月15日 14:27:49
 */
@Component
public class ExecutorConfig {

    @Value("${threadPool.corePoolSize}")
    private Integer coreSize;

    @Value("${threadPool.maxinumPoolSize}")
    private Integer maxinumPoolSize;

    @Value("${threadPool.keepAliveTime}")
    private Integer keepAliveTime;

    @Value("${threadPool.queueCapacity}")
    private Integer queueCapacity;

    @Bean
    @Primary
    public ThreadPoolExecutor threadPoolExecutor() {
        ThreadFactory threadFactory = new CustomizableThreadFactory("threadXXX");
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(coreSize,
                maxinumPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(queueCapacity),
                threadFactory);
        //拒绝策略:队列满了后续任务直接丢弃 不抛出异常
        threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        return threadPoolExecutor;
    }
}
